from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
import Ui_transaksi
import utility
import transaksiEdit

#ID_TRANSAKSI, ID_PELANGGAN,  NO_TRANS, TGL_TRANS, DISETOR_OLEH, TOTAL_RP, POIN, KET, AUDIT_USER, AUDIT_WAKTU, STATUS, CC_TIPE, NO_CC, SPEC_STORE = range(14)
TGL_TRANS, NO_TRANS, NAMA,  NO_KARTU,  ID_PELANGGAN, TOTAL_RP, POIN, CC_TIPE, SPEC_STORE, DISETOR_OLEH, ID_TRANSAKSI = range(11)

class Transaksi(QDialog, Ui_transaksi.Ui_TransaksiDlg):
  def __init__(self, dbConn, dataGlob,  parent=None):
        super(Transaksi, self).__init__(parent)
        self.setupUi(self)
        self.initMenu()
        self.tgl_cb.setCheckState(Qt.Checked)
        self.tgl_aw.setDate(QDate.currentDate())
        self.tgl_ak.setDate(QDate.currentDate())
        self.db = dbConn
        self.dataGlob = dataGlob
        self.util = utility.Utility(self.db)
        
        self.plgModel = QSqlQueryModel(self)
        self.plgModel.setHeaderData(TGL_TRANS, Qt.Horizontal, QVariant("Tgl Trans"))
        self.plgModel.setHeaderData(NO_TRANS, Qt.Horizontal, QVariant("No Trans"))
        self.plgModel.setHeaderData(NAMA, Qt.Horizontal, QVariant("Nama"))
        self.plgModel.setHeaderData(NO_KARTU, Qt.Horizontal, QVariant("No MMC"))
        self.plgModel.setHeaderData(ID_PELANGGAN, Qt.Horizontal, QVariant("ID Pelanggan"))
        self.plgModel.setHeaderData(TOTAL_RP, Qt.Horizontal, QVariant("Total Rp"))
        self.plgModel.setHeaderData(POIN, Qt.Horizontal, QVariant("Poin"))
        self.plgModel.setHeaderData(CC_TIPE, Qt.Horizontal, QVariant("Tipe Kartu"))
        self.plgModel.setHeaderData(SPEC_STORE, Qt.Horizontal, QVariant("Jenis Toko"))
        self.plgModel.setHeaderData(DISETOR_OLEH, Qt.Horizontal, QVariant("Disetor Oleh"))
        self.plgModel.setHeaderData(ID_TRANSAKSI, Qt.Horizontal, QVariant("ID Dok"))
        
        self.masterTv.setModel(self.plgModel)
        self.masterTv.setItemDelegate(MasterDelegate(self))
        self.masterTv.setSelectionMode(QTableView.SingleSelection)
        self.masterTv.setSelectionBehavior(QTableView.SelectRows)
        self.connect(self.masterTv.selectionModel(), SIGNAL("currentRowChanged(QModelIndex,QModelIndex)"), self.rowChanged)
        
        self.detModel = QSqlQueryModel(self)
        self.detModel.setHeaderData(2, Qt.Horizontal, QVariant("No Bukti"))
        self.detModel.setHeaderData(3, Qt.Horizontal, QVariant("Toko"))
        self.detModel.setHeaderData(4, Qt.Horizontal, QVariant("Jumlah (Rp)"))
        
        self.detailTv.setModel(self.detModel)
        self.detailTv.setItemDelegate(DetailDelegate(self))
        self.detailTv.setSelectionMode(QTableView.SingleSelection)
        self.detailTv.setSelectionBehavior(QTableView.SelectRows)
        
  @pyqtSignature("")
  def on_noMmc_editingFinished(self):
      if self.noMmc.text() != "":
          self.noMmc_cb.setCheckState(Qt.Checked)
      else:
          self.noMmc_cb.setCheckState(Qt.Unchecked)
        
  @pyqtSignature("")
  def on_nama_editingFinished(self):
      if self.nama.text() != "":
          self.nama_cb.setCheckState(Qt.Checked)
      else:
          self.nama_cb.setCheckState(Qt.Unchecked)
          
  @pyqtSignature("")
  def on_noDok_editingFinished(self):
      if self.noDok.text() != "":
          self.noDok_cb.setCheckState(Qt.Checked)
      else:
          self.noDok_cb.setCheckState(Qt.Unchecked)
          
  @pyqtSignature("")
  def on_tgl_aw_editingFinished(self):
      self.tgl_cb.setCheckState(Qt.Checked)
          
  @pyqtSignature("")
  def on_tgl_ak_editingFinished(self):
      self.tgl_cb.setCheckState(Qt.Checked)
          
  def initMenu(self):
      self.retrieveAct = QAction(self.tr("Retrieve"), self)
      self.connect(self.retrieveAct, SIGNAL("triggered()"), self.retrieveData)
      self.sortAct = QAction(self.tr("Sort"), self)
      self.addAct = QAction(self.tr("Add"), self)
      self.connect(self.addAct, SIGNAL("triggered()"), self.addData)
      self.editAct = QAction(self.tr("Edit"), self)
      self.connect(self.editAct, SIGNAL("triggered()"), self.editData)
      self.delAct = QAction(self.tr("Delete"), self)
      self.connect(self.delAct, SIGNAL("triggered()"), self.delData)
      self.printAct = QAction(self.tr("Print Preview"), self)

  def retrieveData(self):
      qStr = "select t.tgl_trans, t.no_trans, p.nama, p.no_kartu, t.id_pelanggan, t.total_rp, t.poin, t.cc_tipe, t.spec_store, t.disetor_oleh, t.id_transaksi from transaksi t left outer join pelanggan p on p.id_pelanggan = t.id_pelanggan"
      
      filt = ""
      urut = " order by tgl_trans "
      if self.noMmc_cb.checkState() == Qt.Checked:
          filt = filt + " p.no_kartu like '"+self.noMmc.text()+"%' and "
      if self.nama_cb.checkState() == Qt.Checked:
          filt = filt + " p.nama like '"+self.nama.text()+"%' and "
      if self.noDok_cb.checkState() == Qt.Checked:
          filt = filt + " t.no_trans like '"+self.noDok.text()+"%' and "
      if self.tgl_cb.checkState() == Qt.Checked:
          filt = filt + " t.tgl_trans between '"+self.tgl_aw.date().toString("yyyy-MM-dd")+"' and '"+self.tgl_ak.date().toString("yyyy-MM-dd")+"' and "
          
      if filt != "":
          filt = " where "+filt.left(len(filt)-4)
          
      qStr = qStr + filt + urut
      self.plgModel.setQuery(qStr, self.db)
      self.masterTv.setColumnHidden(ID_TRANSAKSI, True)
      self.masterTv.setColumnHidden(ID_PELANGGAN, True)
      self.masterTv.setColumnWidth(NO_TRANS, 150)
      self.masterTv.setColumnWidth(NAMA, 250)
      self.masterTv.setColumnWidth(NO_KARTU, 100)
      self.masterTv.setColumnWidth(TOTAL_RP, 150)
#      headView = QHeaderView(Qt.Horizontal)
#      self.masterTv.setVerticalHeader(headView.setDefaultSectionSize(50))
      self.masterTv.resizeRowsToContents()
      self.hitungTotal()
    
  def addData(self):
      form = transaksiEdit.TransaksiEdit(self.db, "add",  self.dataGlob, self)
      form.show()

  def editData(self):
      index = self.masterTv.currentIndex()
      if index.isValid():
          brs = self.plgModel.record(index.row())
          id = brs.value("id_transaksi").toString()
          tgl = brs.value("tgl_trans").toDate()
          if tgl != self.util.getServerToday().date():
              if self.dataGlob["level"] != "ADM":
                  QMessageBox.information(self, "Transaksi","Tidak bisa edit data.")
                  return
          form = transaksiEdit.TransaksiEdit(self.db, id, self.dataGlob, self)
          form.show()

  def delData(self):
      index = self.masterTv.currentIndex()
      if index.isValid():
          brs = self.plgModel.record(index.row())
          id = brs.value("id_transaksi").toString()
          noDok = brs.value("no_trans").toString()
          tgl = brs.value("tgl_trans").toDate()
          if tgl != self.util.getServerToday().date():
              if self.dataGlob["level"] != "ADM":
                  QMessageBox.information(self, "Transaksi","Tidak bisa hapus data.")
                  return
          if QMessageBox.question(self, "Transaksi","Delete Dok No : "+noDok+"?", QMessageBox.Yes|QMessageBox.No) == QMessageBox.Yes:
              qMast = QSqlQuery(self.db)
              qDet = QSqlQuery(self.db)
              self.db.transaction()
              qDet.exec_("delete from transaksi_det where id_transaksi = '"+id+"'")
              qMast.exec_("delete from transaksi where id_transaksi = '"+id+"'")
              self.db.commit()
              self.retrieveData()

  def sortData(self):
       qStr = "select id_pelanggan, kode_pelanggan, nama, no_kartu, alamat1, kota1 from pelanggan"
       self.plgModel.setQuery(qStr, self.db)

  def printData(self):
       qStr = "select id_pelanggan, kode_pelanggan, nama, no_kartu, alamat1, kota1 from pelanggan"
       self.plgModel.setQuery(qStr, self.db)

  def contextMenuEvent(self, event):
        menu = QMenu(self)
        menu.addAction(self.retrieveAct)
        menu.addAction(self.sortAct)
        menu.addSeparator()
        menu.addAction(self.addAct)
        menu.addAction(self.editAct)
        menu.addSeparator()
        menu.addAction(self.delAct)
        menu.addSeparator()
        menu.addAction(self.printAct)
        menu.exec_(event.globalPos())

  def rowChanged(self):
      index = self.masterTv.currentIndex()
      if index.isValid():
          record = self.plgModel.record(index.row())
          id = record.value("id_transaksi").toString()
          qStr = "select id_transaksi, urut, no_bukti, tempat_trans, jumlah, status from transaksi_det where id_transaksi = '"+id+"'"
          self.detModel.setQuery(qStr, self.db)
      self.detailTv.setColumnHidden(0, True)
      self.detailTv.setColumnHidden(1, True)
      self.detailTv.setColumnHidden(5, True)      
      self.detailTv.setColumnWidth(2, 250)
      self.detailTv.setColumnWidth(3, 250)
      self.detailTv.setColumnWidth(4, 350)
      self.detailTv.resizeRowsToContents()
      
  def hitungTotal(self):
      totBrs = self.plgModel.rowCount()
      rpTot = 0
      poinTot = 0
      for i in range(totBrs):
          record = self.plgModel.record(i)
          rpTot += record.value(TOTAL_RP).toDouble()[0]
          poinTot += record.value(POIN).toDouble()[0]
      self.totalRp.setText(str(rpTot))
      self.totalPoin.setText(str(poinTot))

class MasterDelegate(QSqlRelationalDelegate):
    def __init__(self, parent=None):
        super(MasterDelegate, self).__init__(parent)
        
    def paint(self, painter, option, index):
        myoption = QStyleOptionViewItem(option)
        if index.column() == TOTAL_RP or index.column() == POIN:
            myoption.displayAlignment |= Qt.AlignRight|Qt.AlignVCenter
        QSqlRelationalDelegate.paint(self, painter, myoption, index)
        
    def createEditor(self, parent, option, index):
        if index.column() == TGL_TRANS:
            editor.setMaximumDate(QDate.currentDate())
            editor.setDisplayFormat("yyyy-MM-dd")
            if PYQT_VERSION_STR >= "4.1.0":
                editor.setCalendarPopup(True)
            editor.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
            return editor
        else:
            return QSqlRelationalDelegate.createEditor(self, parent,option, index)
            
    def setEditorData(self, editor, index):
        if index.column() == TGL_TRANS:
            date = index.model().data(index, Qt.DisplayRole).toDate()
            editor.setDate(date)
        else:
            QSqlRelationalDelegate.setEditorData(self, editor, index)
            
    def setModelData(self, editor, model, index):
        if index.column() == TGL_TRANS:
            model.setData(index, QVariant(editor.date()))
        else:
            QSqlRelationalDelegate.setModelData(self, editor, model, index)
            

class DetailDelegate(QSqlRelationalDelegate):
    def __init__(self, parent=None):
        super(DetailDelegate, self).__init__(parent)
        
    def paint(self, painter, option, index):
        myoption = QStyleOptionViewItem(option)
        if index.column() == 4:
            myoption.displayAlignment |= Qt.AlignRight|Qt.AlignVCenter
        QSqlRelationalDelegate.paint(self, painter, myoption, index)
        
if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    form = Transaksi()
    form.show()
    app.exec_()
